package com.ccp.dev.system.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.system.dao.SysTypeKeyDao;
import com.ccp.dev.system.model.GlobalType;
import com.ccp.dev.system.model.SysTypeKey;
import com.ccp.dev.system.service.GlobalTypeService;
import com.ccp.dev.system.service.SysTypeKeyService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * GlobalType 控制器类
 *
 * @author caishaofan
 */
@Controller
@Action(ownermodel = SysAuditModelType.SYSTEM_SETTING)
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_SYSTEM + "/globalType")
public class GlobalTypeController extends SysBaseController {

    @Resource
    private GlobalTypeService globalTypeService;

    @Resource
    private SysTypeKeyService sysTypeKeyService;

    @Resource
    private SysTypeKeyDao sysTypeKeyDao;

    /**
     * 声明类型为Long的常量ZERO_LONG
     */
    public final Long ZERO_LONG = 0L;

    /**
     * 声明类型为Integer的常量ZERO_INTEGER
     */
    public final Integer ZERO_INTEGER = 0;


    /**
     * 跳转至list页面
     * @return
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    public String viewList(){
        return "globalType/list";
    }

    /**
     * 根据catKey获取分类
     * catKey：分类key
     * hasRoot：是否有根节点。1,有根节点;0,无根节点。
     * treeType：0代表ztree树，1代表layui树
     * @param request 请求
     * @return ResultData
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="全局分类根据catKey获取分类",
            detail="根据catKey获取分类<#if success>成功<#else>失败</#if>",
            exectype = "查询日志")
    public ResultData getByCatKey(HttpServletRequest request){
        try{
            SysAuditThreadLocalHolder.putParamerter("success", true);
            String treeType= RequestUtil.getString(request,"treeType");
            String catKey= RequestUtil.getString(request,"catKey");
            boolean hasRoot=RequestUtil.getInt(request, "hasRoot",1)==1;
            List<GlobalType> list=globalTypeService.getByCatKey(catKey, hasRoot,treeType);
            return getResultDataSuccess("operation.success",list);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataSuccess("operation.failure");
        }
    }

    @RequestMapping("/queryAllTypeKey")
    @ResponseBody
    public ResultData getAllTypeKey(){
        List<SysTypeKey> sysTypeKeyList = this.sysTypeKeyService.queryAllTypeKey();
        return getResultDataSuccess("operation.success",sysTypeKeyList);
    }

    /**
     * 页面跳转 添加编辑页面
     * @param request 请求
     * @param map 参数
     * @return 页面路径
     * @throws Exception 异常
     */

    //TODO 这个方法和getListAddEditView方法，除了页面不一样，还有啥区别，是不是可以抽取出公共方法
    @Action(description="全局分类添加编辑页面页面跳转",exectype = "页面跳转日志")
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/addNode")
    public String getAddEditView(HttpServletRequest request, ModelMap map)throws Exception{
        //是否根节点
        int isRoot=RequestUtil.getInt(request,"isRoot",0);
        //父节点
        String parentId=RequestUtil.getString(request,"parentId");
        //自己的id
        String typeId=RequestUtil.getString(request,"typeId");
        //是否所属用户
        int isPrivate=RequestUtil.getInt(request,"isPrivate",0);

        String parentName="";
        GlobalType globalType = null;
        boolean isDict=false;
        if(!("".equals(typeId))){
            //修改
            globalType= globalTypeService.getOneById(typeId);
            parentId=globalType.getParentId();
            GlobalType parentGlobalType= globalTypeService.getOneById(parentId);
            if(parentGlobalType==null){
                SysTypeKey sysTypeKey = sysTypeKeyDao.getById(parentId);
                parentName = sysTypeKey.getTypeName();
            }else{
                parentName=parentGlobalType.getTypeName();
            }
            isDict=globalType.getCatKey().equals(GlobalType.CAT_DIC);
        }else{
            //添加
            GlobalType tmpGlobalType=globalTypeService.getInitGlobalType(isRoot,parentId);
            parentName=tmpGlobalType.getTypeName();
            isDict=tmpGlobalType.getCatKey().equals(GlobalType.CAT_DIC);
            globalType=new GlobalType();
            globalType.setType(tmpGlobalType.getType());
            globalType.setTypeName("");
            globalType.setNodeKey("");
        }
        map.put("globalType",globalType);
        map.put("parentId",parentId);
        map.put("isRoot",isRoot);
        map.put("isDict",isDict);
        map.put("typeId",typeId);
        map.put("parentName", parentName);
        map.put("isPrivate", isPrivate);
        map.put("isAdd",RequestUtil.getBoolean(request,"isAdd"));
        map.put("isShow",RequestUtil.getBoolean(request,"isShow"));
        map.put("isGlobalType",RequestUtil.getBoolean(request,"isGlobalType"));
        map.put("type",globalType.getType());
        return "globalType/addNode";
    }

    /**
     * 页面跳转 添加编辑页面
     * @param request 请求
     * @param map 参数
     * @return 页面路径
     * @throws Exception 异常
     */
    @Action(description="全局分类添加编辑页面页面跳转listAddNode",exectype = "页面跳转日志")
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/listAddNode")
    public String getListAddEditView(HttpServletRequest request, ModelMap map)throws Exception{
        //是否根节点
        int isRoot=RequestUtil.getInt(request,"isRoot",0);
        //父节点
        String parentId=RequestUtil.getString(request,"parentId");
        //自己的id
        String typeId=RequestUtil.getString(request,"typeId");
        //是否所属用户
        int isPrivate=RequestUtil.getInt(request,"isPrivate",0);

        String parentName="";
        GlobalType globalType = null;
        boolean isDict=false;
        if(!("".equals(typeId))){
            //修改
            globalType= globalTypeService.getOneById(typeId);
            parentId=globalType.getParentId();
            GlobalType parentGlobalType= globalTypeService.getOneById(parentId);
            if(parentGlobalType==null){
                SysTypeKey sysTypeKey = sysTypeKeyDao.getById(parentId);
                parentName = sysTypeKey.getTypeName();
            }else{
                parentName=parentGlobalType.getTypeName();
            }
            isDict=globalType.getCatKey().equals(GlobalType.CAT_DIC);
        }else{
            //添加
            GlobalType tmpGlobalType=globalTypeService.getInitGlobalType(isRoot,parentId);
            parentName=tmpGlobalType.getTypeName();
            isDict=tmpGlobalType.getCatKey().equals(GlobalType.CAT_DIC);
            globalType=new GlobalType();
            globalType.setType(tmpGlobalType.getType());
            globalType.setTypeName("");
            globalType.setNodeKey("");
        }

        map.put("globalType",globalType);
        map.put("parentId",parentId);
        map.put("isRoot",isRoot);
        map.put("isDict",isDict);
        map.put("typeId",typeId);
        map.put("parentName", parentName);
        map.put("isPrivate", isPrivate);
        map.put("isAdd",RequestUtil.getBoolean(request,"isAdd"));
        map.put("isShow",RequestUtil.getBoolean(request,"isShow"));
        map.put("isGlobalType",RequestUtil.getBoolean(request,"isGlobalType"));
        map.put("type",globalType.getType());
        return "globalType/listAddNode";
    }

    /**
     * 添加或更新系统分类。
     * @param request 请求
     * @throws Exception 异常
     */
    @Action(description="添加或更新全局分类",detail="<#if StringUtil.isEmpty(typeId)>新增<#else>更新</#if>全局分类【${typeName}】<#if success>成功<#else>失败</#if>",exectype = "编辑日志")
    @RequestMapping(UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @ResponseBody
    public Object addUpdate(HttpServletRequest request){
       try{
           SysAuditThreadLocalHolder.putParamerter("success", true);
           String typeId=RequestUtil.getString(request, "typeId");
           String nodeName=RequestUtil.getString(request, "typeName");
           String nodeKey=RequestUtil.getString(request, "nodeKey");
           Integer type = RequestUtil.getInt(request,"type");
           String nodeCode = RequestUtil.getString(request,"nodeCode");
           short nodeCodeType = RequestUtil.getShort(request,"nodeCodeType");
           GlobalType globalType=null;
           if(!("".equals(typeId))&&typeId!=null){
               globalType=globalTypeService.getOneById(typeId);
               globalType.setNodeKey(nodeKey);
               globalType.setTypeName(nodeName);
           }else{
               globalType= new GlobalType();
               globalType.setTypeName(nodeName);
               globalType.setNodeKey(nodeKey);
           }
           //父节点
           String parentId=RequestUtil.getString(request, "parentId");
           //是否根节点
           int isRoot=RequestUtil.getInt(request, "isRoot");
           //是否所属用户
           int isPrivate=RequestUtil.getInt(request, "isPrivate",0);
           //用户id
           String userId= ContextUtil.getCurrentUserId();
           if(StringUtil.isEmpty(typeId)){
               Integer depth=0;
               if(!("".equals(parentId))&&parentId!=null){
                   GlobalType parentGlobal=globalTypeService.getOneById(parentId);
                   if(parentGlobal!=null){
                       parentGlobal.setIsLeaf(1);
                       depth = parentGlobal.getDepth();
                       globalTypeService.update(parentGlobal);
                   }
               }
               GlobalType tmpGlobalType=globalTypeService.getInitGlobalType(isRoot,parentId);
               String catKey=tmpGlobalType.getCatKey();
               if(StringUtil.isNotEmpty(nodeKey)&&StringUtil.isNotEmpty(nodeName)){
                   //判断节点是否重复
                   boolean isExist=globalTypeService.isNodeKeyExists(catKey, nodeKey);
                   //判断节点名称是否重复
                   boolean isExists=globalTypeService.isNodeNameExists(catKey,nodeName);

                   if(isExist&&isExists){
                       SysAuditThreadLocalHolder.putParamerter("success", false);
                       return getResultDataError("globalType.nodeKeyAndNameExist.warning");
                   }
                   if(isExist){
                       SysAuditThreadLocalHolder.putParamerter("success", false);
                       return getResultDataError("globalType.nodeKeyExist.warning");
                   }
                   if(isExists){
                       SysAuditThreadLocalHolder.putParamerter("success", false);
                       return getResultDataError("globalType.nodeNameExist.warning");
                   }
               }

               //分类key不为数据字典的情况
               if(!catKey.equals(GlobalType.CAT_DIC)){
                   globalType.setType(tmpGlobalType.getType());
               }
               //设置用户ID
               if(isPrivate==1){
                   globalType.setUserId(userId);
               }
               globalType.setType(type);
               globalType.setCatKey(catKey);
               globalType.setNodePath(tmpGlobalType.getNodePath());
               globalType.setTypeId(tmpGlobalType.getTypeId());
               globalType.setDepth(depth+1);
               globalType.setSn(ZERO_LONG);
               globalType.setIsLeaf(ZERO_INTEGER);
               globalType.setParentId(parentId);
               globalType.setNodeCode(nodeCode);
               globalType.setNodeCodeType(nodeCodeType);
               //增加租户ID
               String tenid = ContextUtil.getCurrentUserTenantId();
               globalType.setTenantId(tenid);
               globalTypeService.add(globalType);
               return getResultDataSuccess("globalType.add.success");
           }else{
               String catKey=globalType.getCatKey();
               //判断是否存在。
               boolean isExist= globalTypeService.isNodeKeyExistsForUpdate(typeId, catKey, nodeKey);
               if(isExist){
                   SysAuditThreadLocalHolder.putParamerter("success", false);
                   return getResultDataError("globalType.nodeKeyExist.warning");
               }
               globalType.setType(type);
               globalTypeService.update(globalType);
               return getResultDataSuccess("globalType.update.success");
           }
       }catch (Exception e){
           SysAuditThreadLocalHolder.putParamerter("success", false);
           return getResultDataError("operation.failure");
       }
    }

    /**
     * 删除系统分类。
     * @param typeId 分类id
     */
    @Action(description="删除全局分类",detail="删除全局分类<#if success>【${typeName}】成功<#else>失败</#if>",exectype = "删除日志")
    @RequestMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    public Object del(@RequestParam("typeId") String typeId){
        GlobalType globalType = globalTypeService.getOneById(typeId);
        if(BeanUtils.isEmpty(globalType)){
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("delete.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("typeName", globalType.getTypeName());
        int i = globalTypeService.delByTypeId(typeId);
        if (i > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("delete.success");
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("delete.failure");
        }
    }

    /**
     * 获取所有流程分类
     * @return
     * @throws Exception
     */
    @RequestMapping("/flowTypeSelector")
    @Action(description="获取所有流程分类")
    @ResponseBody
    public ResultData flowTypeSelector(HttpServletRequest request)  {
        QueryFilter queryFilter = new QueryFilter(request);
        String tenantId = ContextUtil.getCurrentUserTenantId();
        queryFilter.put("catKey",GlobalType.CAT_FLOW);
        queryFilter.put("tenantId",tenantId);
        List<GlobalType> globalTypeList= globalTypeService.getByCatKey(queryFilter);
        return getResultDataSuccess("query.success",globalTypeList);
    }
    /**
     * 取得个人的分类 系统附件
     * @param request
     * @return
     */
    @RequestMapping("/queryPersonType")
    @Action(description = "取得个人分类")
    @ResponseBody
    public ResultData queryPersonType(HttpServletRequest request){
        String catKey=RequestUtil.getString(request,"catKey");
        boolean hasRoot=RequestUtil.getBoolean(request, "hasRoot",false);
        String userId=ContextUtil.getCurrentUserId();

        List<GlobalType> list=globalTypeService.queryPersonType(catKey,userId, hasRoot);
        return getResultDataSuccess("query.success",list);
    }
}
